<template>
<div class='page-alloc-menu'>
  <el-card>
    <div slot="header">
      <span>分配权限</span>
    </div>
    <div></div>
    <el-tree
      :data="menu"
      :props="defaultProps"
      show-checkbox
      :default-checked-keys="getSelectKeys"
      node-key="id"
      ref="menu-tree"
      default-expand-all>
    </el-tree>
    <el-button type="primary" @click="clearTree">清空</el-button>
    <el-button type="primary" @click="save">保存</el-button>
  </el-card>
</div>
</template>

<script lang='ts'>
import Vue from 'vue'
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '@/apis/menu'
import { Tree } from 'element-ui'
export default Vue.extend({
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      getSelectKeys: [],
      menu: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      }
    }
  },
  created () {
    this.getList()
    this.getRoleMenus()
  },
  methods: {
    async getList () {
      const { data } = await getMenuNodeList()
      this.menu = data
    },
    async getRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      this.getCheckedKeys(data, 1)
    },
    /**
     * @params {*} index: children级数
     */
    getCheckedKeys (menus: any, index: number) {
      menus.forEach((item: any) => {
        if (item.selected && index !== 1) {
          console.log(item.id, item.selected)
          this.getSelectKeys.push(item.id as never)
          // this.getSelectKeys = [...this.getSelectKeys, item.id] as never[]
        }
        if (item.subMenuList) {
          this.getCheckedKeys(item.subMenuList, 2)
        }
      })
      if (this.getSelectKeys) {
        (this.$refs['menu-tree'] as any).setCheckedKeys(this.getSelectKeys)
      }
    },
    // 18086440856
    async save () {
      const menuIdList = (this.$refs['menu-tree'] as Tree).getCheckedKeys()
      await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList
      })
      this.$message.success('处理成功')
      this.$router.back()
    },
    clearTree () {
      (this.$refs['menu-tree'] as Tree).setCheckedKeys([])
    }
  }
})
</script>

<style lang='scss'>

</style>
